package com.zhongpengcheng.blog.auth.matcher;

import cn.hutool.crypto.digest.MD5;
import com.zhongpengcheng.blog.auth.AuthToken;
import com.zhongpengcheng.blog.dao.pojo.db.UserDO;
import com.zhongpengcheng.blog.util.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author ZhongPengCheng
 * @version 1.0
 * @date 2021-08-18 19:36:00
 */
@Slf4j
@Component
public class Md5SaltCredentialsMatcher implements CredentialsMatcher {
    private final MD5 md5 = MD5.create();

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        if (token.getPrincipal() != null) {
            // 到这一步，token的有效性已经验证过了，只要token不为空，就直接放行
            return true;
        }
        AuthToken authToken = (AuthToken) token;
        String username = authToken.getUsername();
        String password = String.valueOf(authToken.getPassword());

        UserDO sysUser = ShiroUtils.getSysUserFromInfo(info);
        String storedUsername = sysUser.getUsername();
        String salt = sysUser.getSalt();
        String storedPassword = info.getCredentials().toString();

        // 密码匹配校验
        return StringUtils.isNoneBlank(username, password, storedPassword, storedPassword, salt)
                && Objects.equals(storedUsername, username)
                && Objects.equals(storedPassword, md5.digestHex(password + salt));
    }
}
